
#include "muduo/prot/codec.h"
#include "muduo/prot/dispatcher.h"
#include "request.pb.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"
#include "muduo/net/TcpConnection.h"

#include <iostream>
#include <unordered_map>
#include <memory>
#include <functional>

class Server
{
public:
    using TranslateRequestptr = std::shared_ptr<xg::TranslateRequest>;
    using AddRequestptr = std::shared_ptr<xg::AddRequest>;
public:
    Server(int port)
        : _TcpServer(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), "Server",
                     muduo::net::TcpServer::kReusePort),
          _dispatcher(std::bind(&Server::onUnknownMessage, this, std::placeholders::_1,
                                std::placeholders::_2, std::placeholders::_3)),
          _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, std::placeholders::_1,
                           std::placeholders::_2, std::placeholders::_3))
    {
        // 给分发器注册方法,这里需要指明类型
        _dispatcher.registerMessageCallback<xg::AddRequest>(std::bind(&Server::OnAdd,this,std::placeholders::_1,
                           std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<xg::TranslateRequest>(std::bind(&Server::OnTranslate,this,std::placeholders::_1,
                           std::placeholders::_2, std::placeholders::_3));

        //给服务器设置回调函数
        //收到消息后的回调函数
        _TcpServer.setMessageCallback(std::bind(&ProtobufCodec::onMessage,&_codec,std::placeholders::_1,
                            std::placeholders::_2, std::placeholders::_3));
        //连接变化的回调函数
        _TcpServer.setConnectionCallback(std::bind(&Server::OnConnection,this,std::placeholders::_1));
    }
    void start()
    {
        _TcpServer.start();
        _baseloop.loop();
    }

private:
    //连接发生变化时的回调函数
    void OnConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            std::cout<<"新连接建立!!!"<<std::endl;
        }
        else
        {
            std::cout<<"连接断开!!!"<<std::endl;
        }
    }
    // 收到一条翻译消息的处理方法
    void OnTranslate(const muduo::net::TcpConnectionPtr &conn,
                   const TranslateRequestptr &message,
                   muduo::Timestamp)
    {
        std::string req_msg=message->msg();
        std::string resp_msg=translate(req_msg);
        xg::TranslateResponse resp;
        //构建响应
        resp.set_msg(resp_msg);
        //发送响应
        _codec.send(conn,resp);
    }
    std::string translate(std::string str)
    {
        static std::unordered_map<std::string, std::string> dict_map = {
            {"hello", "你好"},
            {"Hello", "你好"},
            {"你好", "hello"},
            {"ILoveYou", "奥迪a6"}};
        auto it = dict_map.find(str);
        if (it != dict_map.end())
        {
            return it->second;
        }
        return "unkown\n";
    }
    // 收到一个加法消息的处理方法
    void OnAdd(const muduo::net::TcpConnectionPtr &conn,
               const AddRequestptr &message,
               muduo::Timestamp)
    {
        int num1=message->num1();
        int num2=message->num2();
        int result=num1+num2;
        xg::AddResponse resp;
        resp.set_result(result);
        _codec.send(conn,resp);
    }

    // 给分发器设置一个默认的消息处理，当请求消息的种类不存在时调用
    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn,
                          const MessagePtr &message,
                          muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }

private:
    muduo::net::EventLoop _baseloop;  // 事件循环
    muduo::net::TcpServer _TcpServer; // 服务器
    ProtobufDispatcher _dispatcher;   // 请求分发器对象，每一种请求对应一个回调方法
    ProtobufCodec _codec;             // protobuf协议处理器，将收到的消息通过协议 进行序列化和反序列化
    // 再通过分发器完成业务层面的处理
};


int main()
{
    Server server(8081);
    server.start();
    
    return 0;
}